package com.atguigu.day03;

import org.apache.flink.api.common.functions.Partitioner;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Example5 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .fromElements(1,2,3,4)
                .shuffle()
                .print("随机发送：")
                .setParallelism(2);

        env
                .fromElements(1,2,3,4)
                .rebalance()
                .print("平均分配：")
                .setParallelism(2);

        env
                .fromElements(1,2,3,4)
                .broadcast()
                .print("广播：")
                .setParallelism(2);

        // global 将数据发送到下游的第0个任务插槽
        env
                .fromElements(1,2,3,4)
                .global()
                .print("global：")
                .setParallelism(2);

        env
                .fromElements(1,2,3,4)
                .partitionCustom(
                        new Partitioner<Integer>() {
                            @Override
                            public int partition(Integer key, int numPartitions) {
                                // 将数据发送到这个数据的key对应的任务插槽
                                // 2到达以后，2的key是0,所以将2发送到第0个任务槽
                                // 返回值就是要发送到的任务槽的索引值
                                return key;
                            }
                        },
                        // 指定key的操作
                        new KeySelector<Integer, Integer>() {
                            @Override
                            public Integer getKey(Integer value) throws Exception {
                                // 对1指定key为1,对2指定key为0
                                return value % 2;
                            }
                        }
                )
                .print("自定义分区")
                .setParallelism(2);

        env.execute();
    }
}
